package com.liang.lollipop.lreader.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.BaseTransientBottomBar;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.liang.lollipop.lreader.R;
import com.liang.lollipop.lreader.base.BaseActivity;
import com.liang.lollipop.lreader.base.BaseHolder;
import com.liang.lollipop.lreader.bean.ModelBean;
import com.liang.lollipop.lreader.util.LItemTouchHelper;
import com.liang.lollipop.lreader.util.ModelDAO;
import com.liang.lollipop.lreader.util.TaskUtils;

import java.util.ArrayList;
import java.util.Collections;

/**
 * Created by Lollipop on 2017/09/08.
 * 预设模块的管理及排序Activity
 */
public class ModelManagerActivity extends BaseActivity {

    private ArrayList<ModelBean> modelBeen;
    private Adapter adapter;
    private RecyclerView recyclerView;
    private ModelDAO modelDAO;

    private static final int WHAT_MOVE = 12;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_model_manager);
        setToolBar(R.id.activity_model_manager_toolbar);
        initView();
        initData();
    }

    private void initView(){
        modelBeen = new ArrayList<>();

        recyclerView = (RecyclerView) findViewById(R.id.activity_model_manager_recycler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        LItemTouchHelper helper = LItemTouchHelper.newInstance(recyclerView,this);
        helper.setCanDrag(true);
        helper.setCanSwipe(true);
        recyclerView.setAdapter(adapter = new Adapter(LayoutInflater.from(this),modelBeen,helper));
        adapter.notifyDataSetChanged();
    }

    private void initData(){
        modelDAO = new ModelDAO(this);
        TaskUtils.addTask(new TaskUtils.OnUICallBack<ArrayList<ModelBean>,ModelDAO>(this) {
            @Override
            public void onUISuccess(ArrayList<ModelBean> result) {
                modelBeen.clear();
                if(result!=null)
                    modelBeen.addAll(result);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onUIError(Exception e, int code, String msg) {
                T(getString(R.string.error_model_list)+e.getLocalizedMessage());
            }

            @Override
            public ArrayList<ModelBean> onBackground(ModelDAO[] args) throws Exception {
                ModelDAO dao = args[0];
                return dao.selectAll();
            }
        },modelDAO);
    }

    private class Adapter extends RecyclerView.Adapter<Holder>{

        private LayoutInflater inflater;
        private ArrayList<ModelBean> dataBeen;
        private LItemTouchHelper helper;

        Adapter(LayoutInflater inflater, ArrayList<ModelBean> dataBeen, LItemTouchHelper helper) {
            this.inflater = inflater;
            this.dataBeen = dataBeen;
            this.helper = helper;
        }

        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder holder = Holder.newInstance(inflater,parent);
            holder.setHelper(helper);
            return holder;
        }

        @Override
        public void onBindViewHolder(Holder holder, int position) {
            holder.onBind(dataBeen.get(position));
        }

        @Override
        public int getItemCount() {
            if(dataBeen!=null)
                return dataBeen.size();
            return 0;
        }
    }

    private static class Holder extends BaseHolder implements View.OnTouchListener{

        private static final int LAYOUT_ID = R.layout.item_model;
        private static final int MOVE_BTN = R.id.item_model_swap;
        private static final int CLEAR_BTN = R.id.item_model_clear;

        private TextView titleView;

        static Holder newInstance(LayoutInflater inflater, ViewGroup group){
            return new Holder(inflater.inflate(LAYOUT_ID,group,false));
        }

        Holder(View itemView) {
            super(itemView);
            titleView = (TextView) itemView.findViewById(R.id.item_model_name);
            itemView.findViewById(MOVE_BTN).setOnTouchListener(this);
            itemView.findViewById(CLEAR_BTN).setOnClickListener(this);
            canSwipe = true;
        }

        void onBind(ModelBean bean) {
            super.onBind(bean);
            titleView.setText(bean.name);
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            helper.startDrag(this);
            return true;
        }
    }

    @Override
    public void onSwiped(int adapterPosition) {
        super.onSwiped(adapterPosition);
        if(modelBeen.size()<2){//只剩下一个的时候，不允许删除
            adapter.notifyItemChanged(adapterPosition);
            return;
        }
        ModelBean modelBean = modelBeen.remove(adapterPosition);
        adapter.notifyItemRemoved(adapterPosition);
        Snackbar.make(recyclerView, R.string.deleted,Snackbar.LENGTH_LONG)
                .setAction(R.string.undo, new RecallClickListener(adapterPosition,modelBean,adapter,modelBeen))
                .addCallback(new SwipedCallback(modelDAO,modelBean)).show();
    }

    private class SwipedCallback extends BaseTransientBottomBar.BaseCallback<Snackbar>{
        private ModelDAO dao;
        private ModelBean bean;

        public SwipedCallback(ModelDAO dao, ModelBean bean) {
            this.dao = dao;
            this.bean = bean;
        }

        @Override
        public void onDismissed(Snackbar transientBottomBar, int event) {
            super.onDismissed(transientBottomBar, event);
            if(event==DISMISS_EVENT_ACTION)
                return;
            dao.delete(bean.id);
            sendBroadcast(new Intent(SettingActivity.ACTION_SETTING_CHANGE));
        }
    }

    private class RecallClickListener implements View.OnClickListener{

        private int adapterPosition;
        private ModelBean modelBean;
        private Adapter adapter;
        private ArrayList<ModelBean> data;

        public RecallClickListener(int adapterPosition, ModelBean modelBean, Adapter adapter, ArrayList<ModelBean> data) {
            this.adapterPosition = adapterPosition;
            this.modelBean = modelBean;
            this.adapter = adapter;
            this.data = data;
        }

        @Override
        public void onClick(View v) {
            data.add(adapterPosition,modelBean);
            adapter.notifyItemInserted(adapterPosition);
        }
    }

    @Override
    public void onItemViewClick(RecyclerView.ViewHolder holder, View v) {
        super.onItemViewClick(holder, v);
        switch (v.getId()){
            case Holder.CLEAR_BTN://删除操作
                onSwiped(holder.getAdapterPosition());
                break;
        }
    }

    @Override
    public boolean onMove(int srcPosition, int targetPosition) {
//        Message message = handler.obtainMessage(WHAT_MOVE);
//        message.arg1 = srcPosition;
//        message.arg2 = targetPosition;
//        handler.sendMessage(message);

        ModelBean srcBean = modelBeen.get(srcPosition);
        ModelBean targetBean = modelBeen.get(targetPosition);
        //交换排序数据数据
        int sort = srcBean.sort;
        srcBean.sort = targetBean.sort;
        targetBean.sort = sort;
        //交换位置
        Collections.swap(modelBeen, srcPosition, targetPosition);
        //更新数据
        modelDAO.updates(srcBean,targetBean);
        adapter.notifyItemMoved(srcPosition, targetPosition);
        return true;
    }

    @Override
    protected void onHandler(Message message) {
        super.onHandler(message);
        switch (message.what){
            case WHAT_MOVE:
                break;
        }
    }
}
